package leetcode.lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author huangweiyue
 * @version v1.0
 * @task 146 LRU https://leetcode-cn.com/problems/lru-cache/
 * @description JDK的实现 https://leetcode-cn.com/problems/lru-cache/solution/lruhuan-cun-ji-zhi-by-leetcode-solution/
 * @date Created in 2021-07-05
 */
class LRUCacheUseLinkedHashMap extends LinkedHashMap<Integer, Integer>{
    private int capacity;

    public LRUCacheUseLinkedHashMap(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    public int get(int key) {
        return super.getOrDefault(key, -1);
    }

    public void put(int key, int value) {
        super.put(key, value);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        /*
         * 注意此处逻辑 当map容量等于cap时，说明容量满了，此时需要删除最开始的（也就是第一个），在插入新的，
         * 从而也就理解了为什么accessOrder=true,这样会把最近访问的元素放到双向链表的尾巴处
         */
        return size() > capacity;
    }
}
